<template>
  <div class="page-container">
    <div style="margin-top: 20px">
      <van-cell-group inset>
        <van-cell center="center" size="large" class="stateCardContainer">
          <template #title>
            <p style="color: white;text-align: left;font-weight: bold;font-size: 1.3em">
              <!-- 根据 appointment.appointmentState 显示不同的标题 -->
              {{ appointment.appointmentState === "1" ? '待付款' : appointment.appointmentState === "2" ? '已预约' : appointment.appointmentState === "3" ? '就诊中':appointment.appointmentState === "4" ? '已就诊': '已取消' }}
            </p>
          </template>
          <template #label>
            <p style="color: white;text-align: left;">
              <!-- 根据 appointment.appointmentState 显示不同的标签内容 -->
              {{ appointment.appointmentState === "1" ? '请尽快完成付款！' : appointment.appointmentState === "2" ? '您已成功预约该医生号源！' : appointment.appointmentState === "3" ? '您当前正在就诊': appointment.appointmentState === "4" ? '您已完成就诊！': '您已取消预约！' }}
            </p>
          </template>
          <template #value v-if="appointment.appointmentState === '1' ">
            <van-count-down  :time="time">
              <template #default="timeData">
                <span class="block">{{ timeData.minutes }}</span>
                <span class="colon">:</span>
                <span class="block">{{ timeData.seconds }}</span>
              </template>
            </van-count-down>
          </template>
        </van-cell>
      </van-cell-group>

    </div>

    <div style="margin-top: 20px">
      <van-cell-group inset>
        <van-cell center="center" size="large" class="doctorCardContainer">
          <template #icon>
            <img v-bind:src="require('@/assets/images/doctor.png')" alt="医生图片"
                 style="max-width: 90%; max-height: 90%;border-radius: 50%;margin-right: 20px">
          </template>
          <template #title>
            <p class="title-text">{{ appointment.doctorName }}</p>
          </template>
          <template #label>
            <p class="label-text">{{ appointment.doctorLabel }}</p>
            <p class="label-text">南昌大学第二附属医院</p>
          </template>
        </van-cell>
      </van-cell-group>
    </div>

    <div style="margin-top: 20px">
      <van-cell-group inset class="informationCardContainer">
        <van-cell center="center" size="large">
          <template #title>
            <p style="text-align: left;line-height: 0;font-size: 1.2em;font-weight: bold;">就诊人信息</p>
          </template>
        </van-cell>
        <van-cell center="center" size="large" v-bind:value="appointment.pname"
                  style="font-size:1.1em">
          <template #title>
            <p style="text-align: left;line-height: 0;font-size: 1.1em">就诊人</p>
          </template>
        </van-cell>
        <van-cell center="center" size="large" v-bind:value="appointment.department"
                  style="font-size:1.1em">
          <template #title>
            <p style="text-align: left;line-height: 0;font-size: 1.1em">就诊科室</p>
          </template>
        </van-cell>
        <van-cell center="center" size="large" v-bind:value="appointment.idCardNumber"
                  style="font-size:1.01em">
          <template #title>
            <p style="text-align: left;line-height: 0;font-size: 1.1em">证件号</p>
          </template>
        </van-cell>
        <van-cell center="center" size="large" v-bind:value="appointment.telNumber"
                  style="font-size:1.1em">
          <template #title>
            <p style="text-align: left;line-height: 0; font-size: 1.1em">手机</p>
          </template>
        </van-cell>
        <van-cell center="center" size="large" v-bind:value="appointment.appointmentTime"
                  style="--van-cell-value-color:rgb(79,156,245);font-size:1.1em">
          <template #title>
            <p style="text-align: left;line-height: 0; font-size: 1.1em">就诊时间</p>
          </template>
        </van-cell>
        <van-cell center="center" size="large" v-bind:value="appointment.departmentAddress"
                  style="font-size:1.2em">
          <template #title>
            <p style="text-align: left;line-height: 0; font-size: 1.1em">科室地址</p>
          </template>
        </van-cell>
        <!--        <van-cell center="center" size="large">-->
        <!--          <template #title>-->
        <!--            <p style="text-align: left;line-height: 0; font-size: 1.1em">医事服务费</p>-->
        <!--          </template>-->
        <!--          <template #value>-->
        <!--            <p style="text-align: right;line-height: 0;font-weight: bold;color:rgb(240,167,50);-->
        <!--            font-size:1.4em">-->
        <!--              {{ appointment.serviceFee }}</p>-->
        <!--          </template>-->
        <!--        </van-cell>-->
      </van-cell-group>
    </div>

    <div style="margin-top: 20px">
      <van-cell-group inset class="informationCardContainer">
        <van-cell center="center" size="large">
          <template #title>
            <p style="text-align: left;line-height: 0;font-size: 1.2em;font-weight: bold;">订单详情</p>
          </template>
        </van-cell>
        <van-cell center="center" size="large" v-bind:value="appointment.appointmentNumber"
                  style="font-size:1.1em">
          <template #title>
            <p style="text-align: left;line-height: 0;font-size: 1.1em">医院订单号</p>
          </template>
        </van-cell>
        <van-cell center="center" size="large" v-bind:value="appointment.createTime"
                  style="font-size:1.1em">
          <template #title>
            <p style="text-align: left;line-height: 0;font-size: 1.1em">创建时间</p>
          </template>
        </van-cell>
        <van-cell center="center" size="large">
          <template #title>
            <p style="text-align: left;line-height: 0; font-size: 1.1em">医事服务费</p>
          </template>
          <template #value>
            <p style="text-align: right;line-height: 0;font-weight: bold;color:rgb(240,167,50);
                    font-size:1.4em">
              {{ appointment.serviceFee }}</p>
          </template>
        </van-cell>
      </van-cell-group>
    </div>

    <van-sticky v-if="appointment.appointmentState === '1' " :offset-bottom="0" position="bottom">
      <div class="payment-bottom">
        <p class="payment-amount">支付金额：{{ appointment.serviceFee }}</p>
        <van-button type="primary" class="payment-button" @click="onClickPay">支付</van-button>
      </div>
    </van-sticky>

    <van-sticky v-else-if="appointment.appointmentState === '2'" :offset-bottom="0" position="bottom">
      <div class="payment-bottom">
        <p class="payment-amount">出示二维码在前台签到</p>
        <a @click="cancelAppointment">取消</a>
        <van-button type="primary" class="payment-button" @click="showRegisteredDetail">显示二维码</van-button>
      </div>
    </van-sticky>
  </div>
</template>

<script setup>
import {onBeforeMount, ref} from 'vue';
import {AppointmentService, PayService} from "@/api/api";
import router from "@/router";
import {showConfirmDialog} from "vant";
const appointmentId = ref(-1);
onBeforeMount(async () => {
  appointmentId.value = history.state.appointmentId;

  if(appointmentId.value !== undefined)
    await loadData(); // 在页面加载完成后调用加载数据的方法
});
async function loadData() {
  // 加载数据
  try {
    if(appointmentId.value === -1)
      return;
    const response = await AppointmentService.getPatientDetail(appointmentId.value);
    // 获取响应数据
    appointment.value = response.data;
    const currentTime = new Date().getTime();
    const createTime = new Date(appointment.value.createTime).getTime();
    const timeDifference = 15 * 60 * 1000 + createTime - currentTime; // 差值（单位：毫秒）

    time.value = timeDifference;
    console.log(currentTime);
    console.log(time.value);
    console.log(appointment.value);
  } catch (error) {
    console.error(error); // 处理错误
  }
}
const cancelAppointment = () => {
  console.log(111);
  showConfirmDialog(
    {
      title: '提示',
      message: '是否取消该预约？',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      async beforeClose(action) {
        if (action === 'confirm') {  //点击确认
          const response = await AppointmentService.cancelAppointment(appointmentId.value);
          console.log(response);
          if(appointmentId.value !== undefined)
            await loadData(); // 在页面加载完成后调用加载数据的方法
          return true;
        } else {
          console.log(111);
          return false;
        }
      }
    }
  )
};

const time = ref(30 * 60 * 60 * 1000);
const appointment = ref({
  pname: "曹锦琦",
  department: "中医科门诊",
  idCardNumber: "124534********0039",
  telNumber: "13603203520",
  appointmentTime: "2023-11-30 09:00~09:30",
  departmentAddress: "暂无",
  appointmentNumber: '0023295922',
  createTime: '2023-11-30 10:00:00',
  serviceFee: '￥100.00',
  doctorName: '李超',
  doctorLabel: '心内主任医师 心内科门诊(南区)',
  appointmentState: 1
});

const onClickPay = async () => {
  const order = ref({
    out_trade_no: appointment.value.appointmentNumber,
    subject: '南昌大学第二附属医院挂号费用',
    total_amount: appointment.value.serviceFee,
  });

  try {
    const response = await PayService.pay(order.value); // 调用PayService的pay方法，并传入payInfo参数
    console.log(response);
    const divForm = document.getElementsByTagName('div');
    if (divForm.length) {
      document.body.removeChild(divForm[0]);
    }
    const div = document.createElement('div');
    div.innerHTML = response.data.msg; // data就是接口返回的form表单字符串
    document.body.appendChild(div);
    document.forms[0].setAttribute(
        'target', '_self'); // 新开窗口跳转
    document.forms[0].submit();
  } catch (error) {
    console.error(error); // 处理错误
  }
};

const showRegisteredDetail = async () => {
  try {
    const data = {
      appointmentId: appointmentId.value
    }

    await router.push({
      path: '/RegisteredDetail',
      state: data
    });

  } catch (error) {
    console.error(error);
  }
}
</script>

<style scoped>
.doctorCardContainer {
  height: 100px;
}

.informationCardContainer {
  --van-cell-font-size: 14px;
}

.label-text {
  text-align: left;
  line-height: 0.8;
}

.title-text {
  text-align: left;
  line-height: 0.8;
  font-weight: bold;
}

.page-container {
  position: relative;
  min-height: 80vh; /* 设置最小高度以确保按钮在页面底部 */
}

.stateCardContainer{
  height: 100px;
  background: linear-gradient(to right, #3399ff, #53a9ff);
}

.colon {
  display: inline-block;
  margin: 0 4px;
  color: #ffffff;
}
.block {
  display: inline-block;
  width: 50px;
  height: 30px;
  color: #fff;
  font-size: 20px;
  text-align: center;
  background-color: #1989fa;
  line-height: 30px; /* 设置与块元素高度相等的行高 */
}

.payment-bottom {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  background-color: #fff;
  border-top: 1px solid #e5e5e5;;
}

.payment-amount {
  font-size: 16px;
}

.payment-button {
  width: 120px;
}

</style>